import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import styles from './index.less';
import { connect } from 'umi';
import BimTree from '@/components/widgets/BimTree/BimTree.tsx';
import {
  getSlpkBimDirectory,
  getSlpkBimSubDirectory,
  getSlpkBimAllchilds,
} from '@/services/geoplatServices';
import SearchResultList from './SearchResultList';
import { buildingUtils, viewUtils } from '@/utils/arcgis';
// import _get from 'lodash/get';
import _set from 'lodash/set';
import { SearchOutlined, CloseSquareOutlined } from '@ant-design/icons';

// 指向更新节点位置的键值 配合lodash的set使用
const _getKeys = keys => {
  // const len = keys.length
  return keys.reduce((result, key, i) => {
    result.push(key);
    // if (len===1 && i === len-1) {
    //   return result
    // }
    result.push('children');
    return result;
  }, []);
};

const _getTreeDataNode = (e, level = 1, parent = null) => {
  const isString = typeof e === 'string';
  return {
    name: isString ? e : e.name,
    level: isString ? level : e.level,
    children: isString ? [] : e.children,
    parent: isString ? parent : e.parent,
    key: `${isString ? e : e.name}_${level}`,
  };
};

const BimTreePanel = ({
  dispatch,
  onClose,
  bimList,
  currentBimVersion,
  isGlobalProcessRender,
  compareState,
}) => {
  const [isSearch, setIsSearch] = useState(false);
  const [keyword, setKeyword] = useState('');
  const [tData, setTData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const { name: bimName, bimId: curBimId } = currentBimVersion;
  useEffect(() => {
    if (!curBimId) return;
    setIsLoading(true);
    getSlpkBimDirectory(curBimId, 1).then(({ data: _data }) => {
      console.log(_data);
      try {
        const _tData = _data.data.map((e, index) => _getTreeDataNode(e));
        console.log(_tData);
        setTData(_tData);
      } catch (error) {
        setTData([]);
      }

      setIsLoading(false);
    });
  }, [curBimId]);

  const handleTreeChange = bimObj => {
    console.log(bimObj);
    dispatch({ type: 'bimmodel/updateState', payload: { currentBimVersion: bimObj } });
    setIsSearch(false);
  };

  const handlePlaceholderClick = () => {
    dispatch({ type: 'maptoolbar/updataActiveToolbar', payload: 'layerlist' });
  };

  const handleLoadData = async (treeNode, indexArr) => {
    const { _name: name, _level: level, _parent: parent } = treeNode;
    if (level > 3) return;
    const _children = await getSlpkBimSubDirectory(
      curBimId,
      name,
      parent && parent.name,
      level + 1,
    );
    const children = _children.map(e => {
      return { ...e, key: `${e.name}_${e.level}` };
    });
    setTData(data => {
      console.log(indexArr, data, children, '---------');
      const _data = [...data];
      _set(data, _getKeys(indexArr), children);
      console.log(_data);
      return _data;
    });
  };

  const handleViewClick = async (item, isView) => {
    // console.log(item, '==============');
    const { name } = item;
    const view = await viewUtils.isViewReady();
    let subNames = void 0;
    // let subNames: undefined | string[] = void 0;
    if (!isView) {
      if (item.level === 3) {
        subNames = [name];
      } else {
        try {
          const { data: _data } = await getSlpkBimAllchilds(curBimId, name);
          subNames = _data.data;
        } catch (error) {
          console.error('获取叶子节点错误');
        }
      }
    }
    buildingUtils.renderer(view, bimName, subNames);
  };
  console.log('awe',tData, bimName)
  return (
    <div className={classnames(styles.panel, styles.bimTreePanel)}>
      {/* bim树 */}
      <div
        className={classnames(styles.box, styles.bimTreeBox, 'side-panel2', {
          [styles.bimTreeBoxFull]: isGlobalProcessRender,
          [styles.bimTreeBoxHide]: compareState,
        })}
        style={{ position: 'relative' }}
      >
        <div
          className={classnames(styles.head, 'side-panel2-title', {
            [styles.headActive]: isSearch,
          })}
        >
          {!isSearch && 'BIM目录树'}
          <div className={styles.headRight}>
            {/* <div
              className={classnames(styles.btn, styles.searchBtn, {
                [styles.searchBtnActive]: isSearch,
              })}
              onClick={() => setIsSearch(e => !e)}
            /> */}
            <SearchOutlined
              className={classnames(styles.btn, styles.searchBtn, {
                [styles.searchBtnActive]: isSearch,
              })}
              onClick={() => setIsSearch(e => !e)}
            />
            {isSearch && (
              <input
                type="text"
                value={keyword}
                placeholder="输入搜索内容"
                onChange={e => setKeyword(e.target.value)}
                className={styles.headRightInput}
              />
            )}
            <CloseSquareOutlined onClick={onClose}></CloseSquareOutlined>
          </div>
        </div>

        <div className={classnames(styles.body, 'side-panel2-body')}>
          {isSearch ? (
            <SearchResultList
              onPlaceholderClick={handlePlaceholderClick}
              keyword={keyword}
              onItemClick={handleTreeChange}
              models={bimList}
            />
          ) : (
            <BimTree
              loadData={handleLoadData}
              treeData={tData}
              bimName={bimName}
              loading={isLoading}
              onViewClick={handleViewClick}
              height={'calc(100vh - 518px)'}
            />
          )}
        </div>
      </div>
    </div>
  );
};

// export default BimTreePanel;
export default connect(({ bimmodel, app }) => {
  return {
    bimList: bimmodel.bimList,
    compareState: bimmodel.compareState,
    currentBimVersion: bimmodel.currentBimVersion,
    isGlobalProcessRender: app.isGlobalProcessRender,
  };
})(BimTreePanel);
